<template>
	<div id="url-picture-upload">
		<a-input-group compact>
			<a-input v-model:value="fileUrl" style="width: calc(100% - 120px)" placeholder="请输入图片链接" />
			<a-button type="primary" style="width: 120px" :loading="loading" @click="handleUpload">上传</a-button>
		</a-input-group>
		<div class="img-wrapper">
			<img v-if="picture?.url" :src="picture?.url" alt="avatar" />
		</div>
	</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { uploadPictureByUrlUsingPost } from '@/api/pictureController'

interface Props {
	picture?: API.PictureVO
	spaceId?: any
	onSuccess?: (newPicture: API.PictureVO) => void
}

const props = defineProps<Props>()
const fileUrl = ref<string>()

const loading = ref<boolean>(false)

// 图片上传操作
const handleUpload = async () => {
	loading.value = true
	try {
		// 调用上传接口
		const params: API.PictureUploadRequest = { fileUrl: fileUrl.value }
		params.spaceId = props.spaceId
		if (props.picture) {
			params.id = props.picture.id
		}

		const res = await uploadPictureByUrlUsingPost(params)
		if (res.data.code === 0 && res.data.data) {
			message.success('图片上传成功')
			// 将上传图片成功的信息传递给父组件
			props.onSuccess?.(res.data.data)
		} else {
			message.error('图片上传失败，' + res.data.message)
		}
	} catch (error: any) {
		console.error('图片上传失败', error)
		message.error('图片上传失败：' + error.message)
	}
	loading.value = false
}
</script>
<style scoped lang="scss">
#url-picture-upload {
	margin-bottom: 16px;

	img {
		max-width: 100%;
		max-height: 150px;
	}

	.img-wrapper {
		margin-top: 16px;
		text-align: center;
	}
}
</style>
